#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    this->setWindowIcon(QIcon(":/my/Icom.jpg"));
    //加载文件控制系统，父类为窗体
    file = new FileControl(this);
    //播放控制系统
    mediaControl = new MediaControl(this);

    setWindowFlags(Qt::FramelessWindowHint);//去掉标题栏
    //setAutoFillBackground(false);  //这个不设置的话就背景变黑
    setAttribute(Qt::WA_TranslucentBackground,true);
    this->setObjectName("showArea");
    ui->showArea->setStyleSheet("#showArea{border-image: url(:/my/background.jpg);}");

    vol = new QSlider(this);
    vol->setGeometry(648,355,15,140);
    connect(vol,SIGNAL(valueChanged(int)),this,SLOT(setVol(int)));
    vol->setValue(50);
    ui->adjVol->setChecked(false);

    //ui->textBrowser_2->setAttribute(Qt::WA_TranslucentBackground,true);
    //testList设置
    ui->mediaList->setColumnCount(1);
    location_list = new QTreeWidgetItem(ui->mediaList);
    location_list->setText(0,"本地位置");
    FTP_list = new QTreeWidgetItem(ui->mediaList);
    FTP_list->setText(0,"网络位置");

    //自定义一个信号，当完成读取时发送此信号即可
    //后面的程序会先执行，因为FTP程序有延迟
    //如何进行堵塞？
    //while(!file->isFinished());//使用while循环的方式阻塞，等到FTP标志位为true时继续向下
    //这种方法是错误的，程序不会是多线程进行的，此处在while循环中堵死，而不会在其中调用槽函数

    receiver = new QUdpSocket(this);
    receiver->bind(QHostAddress("192.168.1.103"), 2121);
    connect(receiver, SIGNAL(readyRead()),this, SLOT(readPendingDatagrams()));

    connect(mediaControl,SIGNAL(positionChanged(qint64)),this,SLOT(updateSlider(qint64)));
    ui->timeLine->setValue(50);
}

/**
 * @brief Widget::add_PlayerList
 */
void Widget::add_PlayerList(void)
{
    //清除初始本地播放列表
    delete ui->mediaList->takeTopLevelItem(0);
    location_list = new QTreeWidgetItem();
    ui->mediaList->insertTopLevelItem(0,location_list);
    location_list->setText(0,"本地位置");
    //在list面板上显示列表
    QStringList list = file->findMediaFile_Music();//查找
    qDebug()<<list;

    //获取播放列表目录
    mediaControl->setMeidaPath(file->getDirctor());

    for(int count = 0;count < list.length();count++)
    {
        //加入视图播放列表
        QTreeWidgetItem * mediaName = new QTreeWidgetItem(location_list);
        mediaName->setText(0,list.at(count));
        //加入控制播放列表      
        mediaControl->setMeidaName(list.at(count));//设置添加的音频文件名
        mediaControl->addPlayerList();
    }
}

/**
 * @brief Widget::updateSlider
 * @param time
 */
void Widget::updateSlider(qint64 time)
{
    qint64 allTime = mediaControl->duration();
    allTime /= 1000;
    qint64 minutes = allTime/60;
    qint64 seconds = allTime%60;
    ui->end->setText(QString("%1").arg(minutes)+":"+QString("%1").arg(seconds));
    time /= 1000;
    minutes = time/60;
    seconds = time%60;
    ui->begin->setText(QString("%1").arg(minutes)+":"+QString("%1").arg(seconds));
    //ui->timeLine->setValue((time/allTime)*100);
    float now = time , all =allTime;
    ui->timeLine->setValue(int(now*1000/all));
}

void Widget::FTP_addList_Music(QStringList mediaName)
{
    QStringList name;
    name = mediaName.filter("mp3");
    for(int count = 0;count < name.length();count++)
    {
        QTreeWidgetItem * mediaName = new QTreeWidgetItem(FTP_list);
        mediaName->setText(0,name.at(count));
        mediaControl->FTP_setMediaName(name.at(count));
        mediaControl->FTP_addPlayerList();
    }
    qDebug()<<name;
}

Widget::~Widget()
{
    delete ui;
}

void Widget::readPendingDatagrams()
{
    while (receiver->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(receiver->pendingDatagramSize());
        receiver->readDatagram(datagram.data(), datagram.size());
        //数据接收在datagram里
        QString data = QString(datagram);
        ui->textBrowser_2->setText(data);
/* readDatagram 函数原型
qint64 readDatagram(char *data,qint64 maxSize,QHostAddress *address=0,quint16 *port=0)
*/
    }
}

//列表被双击之后
void Widget::on_mediaList_itemDoubleClicked(QTreeWidgetItem *item, int column)
{
    if(item->parent() == location_list)
    {
        mediaControl->setPlaylist_locaton();
        //获取播放文件名
        mediaControl->setCurrentRow(ui->mediaList->currentIndex().row());
        mediaControl->playMedia();
        qDebug()<<item->text(column);
        qDebug()<<ui->mediaList->currentIndex().row();
    }
    if(item->parent() == FTP_list)
    {
        //添加进播放那个列表之后不需要再这样url请求播放了
        mediaControl->setPlaylist_FTP();
        mediaControl->setCurrentRow(ui->mediaList->currentIndex().row());
        mediaControl->FTP_playMedia();
        qDebug()<<ui->mediaList->currentIndex().row();
    }
    ui->play_stop->setChecked(false);
}

void Widget::on_next_clicked()
{
    mediaControl->next();
    qDebug()<<ui->mediaList->topLevelItem(0)->text(0);
    ui->mediaList->setCurrentItem(ui->mediaList->topLevelItem(0)->child(mediaControl->getCurrentRow()),0);
    ui->play_stop->setChecked(false);
}

void Widget::on_previous_clicked()
{
    mediaControl->previous();
    ui->mediaList->setCurrentItem(ui->mediaList->topLevelItem(0)->child(mediaControl->getCurrentRow()),0);
    ui->play_stop->setChecked(false);
}

void Widget::on_play_stop_toggled(bool checked)
{
    if(checked == false)
    {
        //播放状态
        this->setObjectName("play_stop");
        ui->play_stop->setStyleSheet("#play_stop{border-image: url(:/my/stop.png);}");
        mediaControl->play();
    }
    else
    {
        //暂停状态
        this->setObjectName("play_stop");
        ui->play_stop->setStyleSheet("#play_stop{border-image: url(:/my/play.png);}");
        mediaControl->pause();
    }
    qDebug()<<checked;
}

void Widget::on_adjVol_toggled(bool checked)
{
    vol->setVisible(checked);
}

void Widget::setVol(int vol)
{
    mediaControl->setVolume(vol);
}

void Widget::on_setting_clicked()
{
    FileSetWidget * setWidget = new FileSetWidget(this);
    setWidget->show();
    connect(setWidget,SIGNAL(locationPath(QString)),this,SLOT(setLocationPath(QString)));
    connect(setWidget,SIGNAL(FTPConfirm(QString,int,QString,QString,QString)),this,SLOT(setFTPParameter(QString,int,QString,QString,QString)));
}



/**
 * @brief Widget::mousePressEvent
 * @param event
 */
void Widget::mousePressEvent(QMouseEvent *event)
{
    if((event->button() == Qt::LeftButton) && ui->frame->geometry().contains(this->mapFromGlobal(QCursor::pos())))
    {
        QCursor cursor;
        cursor.setShape(Qt::ClosedHandCursor);
        QApplication::setOverrideCursor(cursor);
        offset = event->globalPos() - pos();
    }
}

/**
 * @brief Widget::mouseMoveEvent
 * @param event
 */
void Widget::mouseMoveEvent(QMouseEvent *event)
{
    if((event->buttons() & Qt::LeftButton) && ui->frame->geometry().contains(this->mapFromGlobal(QCursor::pos())))
    {
        QPoint temp;
        temp = event->globalPos() - offset;
        move(temp);
    }
}

/**
 * @brief Widget::mouseReleaseEvent
 * @param event
 */
void Widget::mouseReleaseEvent(QMouseEvent *event)
{
    QApplication::restoreOverrideCursor();
}

void Widget::setLocationPath(QString path)
{
    qDebug()<<path;
    //设置文件控制系统的路径
    file->setDirctor(path);
    //调用添加本地播放列表函数
    add_PlayerList();
}

/**
 * @brief Widget::setFTPParameter
 * @param host
 * @param port
 * @param userName
 * @param password
 * @param path
 */
void Widget::setFTPParameter(QString host, int port, QString userName, QString password, QString path)
{
    file->setFTPParameter(host,port,userName,password,path);

    mediaControl->FTP_setHost(host);
    mediaControl->FTP_setPort(port);
    mediaControl->FTP_setMediaPath(path);
    mediaControl->FTP_setUserName(userName);
    mediaControl->FTP_setPassword(password);

    //FTP_host = host;
    FTP_port = port;
    FTP_path = path;
    FTP_userName = userName;
    FTP_password = password;
    qDebug()<<host;
    qDebug()<<port;
    qDebug()<<userName;
    qDebug()<<password;
    qDebug()<<path;

    file->FTP_Process();
    //加载显示列表和控制列表
    connect(file,SIGNAL(isFinished(QStringList)),this,SLOT(FTP_addList_Music(QStringList)));
}
